<?php
namespace app\command;

use app\common\enum\Setting as SettingEnum;
use app\common\library\pay\engine\Smpay;
use app\common\model\store\Setting;
use app\common\service\Authenticate;
use app\common\service\Pay as ChannelPay;
use app\common\service\Pay;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;


class Test extends Command{
    protected function configure()
    {
        // 指令配置
        $this->setName('test')
            ->addArgument('start', Argument::REQUIRED, '开始执行任务')
            ->setDescription('the perform command');
    }

    protected function init(Input $input, Output $output){
        $start = $input->getArgument('start');
        echo $start;
        return $start == 'start';
    }

    protected function execute(Input $input, Output $output)
    {
        $start = $input->getArgument('start');
        switch ($start){
            //执行进件请求
            case 'pay':
                $output->writeln('the Test program is started.');
                $this->start($input,$output);
                $output->writeln('the Test program is stopped.');
                $output->writeln("☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝☝");
                break;
            case 'encode':
                $this->encode($input,$output);
                break;
            case 'decode':
                $this->decode($input,$output);
                break;
            case 'parse':
                $this->parse($input,$output);
                break;
            case 'order':
                $this->query_order($input,$output);
                break;
            case 'auth':
                $this->auth($input,$output);
                break;
            case 'cash':
                $this->cashAlipay($input,$output);
                break;
            case 'rand':
                $this->randstr($input,$output);
                break;
            default:
                $output->writeln('错误指令!');
                break;
        }
    }

    private function start(Input $input,Output $output){
        $payClass = new Pay();
        $params = [
//            'orderId' => 'SM'.date('YmdHis'),
        'orderId' => '2021081299974892',
            'transAmt' => '100',
            'transType' => '70',
            'cardId' => '6225780604859281',
            'userIp' => '61.140.94.63',
            'add1' => '商品',
            'currency' => 'EUR'
        ];
        $income = $payClass->sendSM('order.pay',$params,getStoreId());
        $output->writeln("---------------------------------------------------------------------");
        $output->writeln("request params: data type -interface[]");
        $output->writeln("httpCode:{$income->getHttpCode()}");
        $response = $income->getResponse();
        $output->writeln("response:");
        dump($response);
        $output->writeln("error:{$income->getError()}");
    }

    private function encode(Input $input,Output $output){
        $setting = new Setting();
        $config = $setting->defaultData();
        $config = $config[SettingEnum::PAY]['values']['engine']['smpay'];
        $smpay = new Smpay($config);
        $data = '{"orderId":"orderId"}';
        $output->writeln("代加密密文:{$data}");
        $enData = $smpay->encrypt($data);
        $enStr = urlencode($enData['data']);
        if($enData['code']){
            $output->writeln("加密后的密文:{$enStr}");
        }else{
            $output->writeln("加密失败");
        }
        $output->writeln("---------end--------------");
    }

    private function decode(Input $input,Output $output){
        $setting = new Setting();
        $config = $setting->defaultData();
        $config = $config[SettingEnum::PAY]['values']['engine']['smpay'];
        $smpay = new Smpay($config);
        $strOld = 'nZwRNASy4UfS9NJcVnPrnPOsy0RUBCgf5gs4oGMGHxmoSoc6zM096sRes%2Bpg+oQXZfZsTy%2FxvYfx70aLx%2FCBn%2FTooUlE%2B92Zgx99dnVE6OGIqtmMa%2Bf75fdqF+1rtftKpwq4tzRdS4oRh807ffshqSsZ33c8ZzNzx7VuVlwelUZes%3D';
        $enStr = trim(urldecode($strOld));
        $output->writeln("待解密数据:{$enStr}");
//        $enStr = trim(urldecode('V%2FVSfED2xYXSvnfULfiqh%2Bvb6MrAhBNh%2BpPIUjAWz6vjLBW3O54n7SM3cYQ4O2LBERS10asBCewyw5rwaoonOiVW0nX5gCNy0nm5HJz8%2FN%2BUFboWNfyeNnNYJZw%2B52%2FttbNWkRq06%2BPiYLkEprZLsIJeW2RELvXx5aipTkA%2Fnrs%3D'));
        $deDataArr = $smpay->decrypt($enStr);
        if($deDataArr['code']){
            $deStr = $deDataArr['data'];
            $output->writeln("解密后的密文:{$deStr}");
        }else{
            $output->writeln("error info:{$deDataArr['msg']}");
        }
        $output->writeln("---------end--------------");
    }

    private function parse(Input $input,Output $output){
        $str = "channelOrderId=oemsys20210812114647b6mf9v&orderTime=20210812114747&transType=70&orderId=2021081255485648&sign=b7c3bdff0282e66ec0c93e42fd826ffd&orderStatus=01&respCode=0000&orderDesc=%E4%BA%A4%E6%98%93%E6%88%90%E5%8A%9F";
        parse_str($str,$data);
        dump($data);
        $output->writeln("---------end--------------");
    }
    //查询订单
    private function query_order(Input $input,Output $output){
        if($this->checkOrder('2021081299974899')){
            $output->writeln("订单查询成功");
        }else{
            $output->writeln("订单查询失败");
        }
    }

    private function checkOrder($orderId){
        //支付通道
        $payClass = new ChannelPay();
        $params = [
            'orderId' => $orderId
        ];
        $order = $payClass->sendSM('order.orderQuery',$params,getStoreId());
        if($order->getCode()){
            $response = $order->getResponse();
            dump($response);
            if($response->data->status == '01'){
                return true;
            }
        }
        return false;
    }
    //实名认证测试
    private function auth(Input $input,Output $output){
        $params = [
            'accountNo' => '6217857500040582246',
            'idCard'=> '430528198708130039',
            'name'=> '张政',
            'mobile' => '18908459468',
        ];
        $auth = Authenticate::sendAuthenticate('authenticate4',$params);
        if($auth->getCode()){
            dump($auth->getResponse());
        }else{
            $output->writeln("error info:{$auth->getMsg()}");
        }
    }

    private function der2pem($der_data) {
        $pem = chunk_split(base64_encode($der_data), 64, "\n");
        $pem = "-----BEGIN CERTIFICATE-----\n".$pem."-----END CERTIFICATE-----\n";
        return $pem;
    }

    private function getOptions(){
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipaydev.com/gateway.do';
        $options->signType = 'RSA2';

        $options->appId = '2021000118604716';

        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCyT2VWlsv/9fvO06l3ve/xUI7Qcd8GyiklQ6D/8KP0BfPmmGVq0VQyxJB7EdizcZrd7Da2RMsSOzi6UX4RaWDU9znV30Z2K2D6Fokf15Zgc7zZTicu0uVykSSYyZ9Yyld1J1MaLicfBVzCL4gYEOMOJ9D3hX76n4At3dGguB9yWuUR/PLrV4pa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Fi8ShpK4uD7bwxb2oYbt/9U86Fypz9j6NKd6PPUm/SINxEEBlBNAKt+PzUDMkgGkJqIiUa+v9rznIvsGhWPKfKLx5WKXsgFpTEa4Vqinc/HTGYQaiZjUuoAu3x5plCNLGaYFQYTdIQBAoGBALTzjSKj+pEBA+ZgRz1sgR6v1ONq9xY5ZNzVNMve4Czd34HGXEJxuJSqzoWpYXxRMSaF9R8zz5xVuq+96ZaH7hHlNNZtP4S05ny3FbSAQv++vTDlvp07RdUCcBj7UQs5SFrjoNOx292BGY/cl7LOyl06m2efubwst2gZ4ZmYXPrQ';

        $options->alipayCertPath = 'alipayCertPublicKey_RSA2.crt';
        $options->alipayRootCertPath = 'alipayRootCert.crt';
        $options->merchantCertPath = 'appCertPublicKey_2021000118604716.crt';

        //注：如果采用非证书模式，则无需赋值上面的三个证书路径，改为赋值如下的支付宝公钥字符串即可
        // $options->alipayPublicKey = '<-- 请填写您的支付宝公钥，例如：MIIBIjANBg... -->';

        //可设置异步通知接收服务地址（可选）
//        $options->notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址，例如：https://www.test.com/callback -->";

        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
//        $options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";



        return $options;
    }
    //支付宝提现申请
    public function cashAlipay(Input $input,Output $output){
        Factory::setOptions($this->getOptions());
        try {
            //2. 发起API调用（以支付能力下的统一收单交易创建接口为例）
            $result = Factory::payment()->common()->create("iPhone6 16G", "20200326235526001", "88.88", "2088002656718920");

            //3. 处理响应或异常
            if (!empty($result->code) && $result->code == 10000) {
                echo "调用成功". PHP_EOL;
            } else {
                echo "调用失败，原因：". $result->msg."，".$result->sub_msg.PHP_EOL;
            }
        } catch (\Exception $e) {
            echo "调用失败，". $e->getMessage(). PHP_EOL;;
        }
    }

    // 打印随机数
    public function randstr(Input $input,Output $output){
        $r = $this->GetRandStr(20);
        $output->writeln($r);
    }
    private function GetRandStr($length){
        //字符组合
        $str = '0123456789';
        $len = strlen($str)-1;
        $randstr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }
}
